package com.ruoyi.tzzl.service.imp;

import com.alibaba.fastjson2.JSONObject;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.tzzl.api.PayApi;
import com.ruoyi.tzzl.domain.WzBalanceChangeRecord;
import com.ruoyi.tzzl.domain.WzProgramUser;
import com.ruoyi.tzzl.domain.WzUserDetails;
import com.ruoyi.tzzl.domain.WzWithdrawalRecord;
import com.ruoyi.tzzl.domain.vo.QueryVo;
import com.ruoyi.tzzl.mapper.WzWithdrawalRecordMapper;
import com.ruoyi.tzzl.service.IWzBalanceChangeRecordService;
import com.ruoyi.tzzl.service.IWzProgramUserService;
import com.ruoyi.tzzl.service.IWzUserDetailsService;
import com.ruoyi.tzzl.service.IWzWithdrawalRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 提现申请Service业务层处理
 *
 * @author by caoyong
 * @date 2022/11/17
 **/
@Service
public class WzWithdrawalRecordServiceImpl extends ServiceImpl<WzWithdrawalRecordMapper, WzWithdrawalRecord> implements IWzWithdrawalRecordService {

    @Autowired
    IWzProgramUserService wzProgramUserService;

    @Autowired
    IWzBalanceChangeRecordService wzBalanceChangeRecordService;

    @Autowired
    IWzUserDetailsService userDetailsService;


    @Override
    public List<WzWithdrawalRecord> selectWzWithdrawalRecordList(QueryVo queryVo) {
        LambdaQueryWrapper<WzWithdrawalRecord> lqw = new LambdaQueryWrapper<>();
        //提现用户id
        if (ObjectUtils.isNotEmpty(queryVo.getWid())){
            lqw.eq(WzWithdrawalRecord::getUserId,queryVo.getWid());
        }
        //提现类型
        if (ObjectUtils.isNotEmpty(queryVo.getWithdrawalType())) {
            lqw.eq(WzWithdrawalRecord::getWithdrawalType, queryVo.getWithdrawalType());
        }
        //提现时间
        if (ObjectUtils.isNotEmpty(queryVo.getStartTime())) {
            lqw.between(WzWithdrawalRecord::getCreateTime, queryVo.getStartTime(), queryVo.getEndTime());
        }
        //提现状态
        if (ObjectUtils.isNotEmpty(queryVo.getWithdrawalState())) {
            lqw.eq(WzWithdrawalRecord::getWithdrawalState, queryVo.getWithdrawalState());
        }
        return this.list(lqw);
    }

    /**
     * 用户提现申请
     *
     * @param queryVo
     */
    @Override
    public boolean applyWithdrawal(QueryVo queryVo) {
        WzWithdrawalRecord wzWithdrawalRecord = new WzWithdrawalRecord();
        WzProgramUser user = wzProgramUserService.getById(queryVo.getId());
        wzWithdrawalRecord.setCreateTime(new Date()); //创建时间
        wzWithdrawalRecord.setMoney(queryVo.getMoney()); //提现金额
        //提现类型
        if (user.getRole().equals("3")) {
            wzWithdrawalRecord.setWithdrawalType("1"); //红娘提现
        } else {
            wzWithdrawalRecord.setWithdrawalType("2"); //团队提现
        }
        wzWithdrawalRecord.setUserId(user.getId()); //用户id
        wzWithdrawalRecord.setWithdrawalWay(queryVo.getWithdrawalWay()); //提现方式
        wzWithdrawalRecord.setWithdrawalState("1"); //提现状态
        wzWithdrawalRecord.setPhone(user.getPhone()); //手机号码
        wzWithdrawalRecord.setName(user.getUserName()); //用户名称
        user.setCarryCommission(user.getCarryCommission()-queryVo.getMoney()); //用户余额扣除提现金额
        wzProgramUserService.updateById(user);
        //添加用户余额记录
        record(13, wzWithdrawalRecord, user);
        return this.save(wzWithdrawalRecord);
    }

    /**添加用户余额记录*/
    private void record(Integer type, WzWithdrawalRecord wzWithdrawalRecord, WzProgramUser user) {
        WzBalanceChangeRecord wzBalanceChangeRecord =new WzBalanceChangeRecord();
        wzBalanceChangeRecord.setType(type); //记录类型
        wzBalanceChangeRecord.setNote("用户提现扣款"); //备注
        wzBalanceChangeRecord.setWname(wzWithdrawalRecord.getName()); //用户姓名
        wzBalanceChangeRecord.setCreateTime(new Date()); //创建时间
        wzBalanceChangeRecord.setCommission(user.getCarryCommission()); //佣金
        wzBalanceChangeRecord.setBalance(user.getFriendc().doubleValue()); //余额
        wzBalanceChangeRecord.setChangeMoney(wzWithdrawalRecord.getMoney()); //变动金额
        wzBalanceChangeRecord.setWid(wzWithdrawalRecord.getUserId()); //用户id
        wzBalanceChangeRecord.setAvatarUrl(user.getAvatarurl()); //头像
        wzBalanceChangeRecordService.save(wzBalanceChangeRecord);
    }

    /**
     * 提现审核
     *
     * @param queryVo
     */
    @Override
    public Boolean audit(QueryVo queryVo) throws AlipayApiException {
        WzWithdrawalRecord wzWithdrawalRecord = this.getById(queryVo.getId());
        WzUserDetails userDetails =userDetailsService.selectWzUserDetailsById(wzWithdrawalRecord.getUserId());
        //审核通过
        if (queryVo.getWithdrawalState().equals("0")) {
            Double money = wzWithdrawalRecord.getMoney(); //提现金额
            Double charge = money * 0.01;  //手续费
            wzWithdrawalRecord.setPoundage(charge); //手续费
            wzWithdrawalRecord.setToTheaccount(money - charge); //实际到账
            wzWithdrawalRecord.setWithdrawalState(queryVo.getWithdrawalState()); //提现状态
            JSONObject jsonObject = PayApi.pay(userDetails.getZfbAccount(),userDetails.getZfbName(),wzWithdrawalRecord.getToTheaccount().toString()); //进行转账操作
            if (jsonObject.getString("msg").equals("Success")){
                System.out.println("成功转账");
                wzWithdrawalRecord.setRef(jsonObject.getString("pay_fund_order_id"));
                wzWithdrawalRecord.setOrderStatus(jsonObject.getString("code"));
            }else{
                System.out.println("失败原因:"+jsonObject.getString("sub_msg"));
                wzWithdrawalRecord.setOrderStatus(jsonObject.getString("code"));
                wzWithdrawalRecord.setWithdrawalState("4"); //状态 - 打款失败
                wzWithdrawalRecord.setCauseFailure(jsonObject.getString("sub_msg"));
            }
        } else if (queryVo.getWithdrawalState().equals("2")) { //审核不通过
            //审核不通过金额原路返回
            WzProgramUser user = wzProgramUserService.getById(wzWithdrawalRecord.getUserId());
            user.setCarryCommission(user.getCarryCommission()+wzWithdrawalRecord.getMoney()); //余额
            wzWithdrawalRecord.setWithdrawalState(queryVo.getWithdrawalState()); //提现状态
            wzWithdrawalRecord.setCauseFailure(queryVo.getCauseFailure()); //审核失败原因
            wzProgramUserService.updateById(user);
            //添加用户余额记录
            record(16, wzWithdrawalRecord, user);
        }
        return this.updateById(wzWithdrawalRecord);
    }

    /**
     * 查询今日提现订单
     */
    @Override
    public List<WzWithdrawalRecord> orderToday() {
        LambdaQueryWrapper<WzWithdrawalRecord> lqw =new LambdaQueryWrapper<>();
        lqw.between(WzWithdrawalRecord::getCreateTime, DateUtils.DateToString(new Date()),DateUtils.DateToString(DateUtils.addTime(new Date(),1)));
        return this.list(lqw);
    }

    /**
     * 查看用户提现金额,待打款金额,可提现金额
     * */
    @Override
    public Map<String, Object> withdrawalAmount(Long id) {
        Map<String ,Object> map =new HashMap<>();
        //查询已打款金额
        Double amount =0D;
        LambdaQueryWrapper<WzWithdrawalRecord> lqw =new LambdaQueryWrapper<>();
        lqw.eq(WzWithdrawalRecord::getUserId,id);
        lqw.eq(WzWithdrawalRecord::getWithdrawalState,"0");
        List<WzWithdrawalRecord> list =  this.list(lqw);
        if (ObjectUtils.isNotEmpty(list)){
            for (int i = 0; i < list.size(); i++) {
                amount +=list.get(i).getToTheaccount();
            }
        }
        map.put("alreadyTransfer",amount); //已打款
        //查询待打款金额
        Double notAmount =0D;
        LambdaQueryWrapper<WzWithdrawalRecord> lqw2 =new LambdaQueryWrapper<>();
        lqw2.eq(WzWithdrawalRecord::getUserId,id);
        lqw2.eq(WzWithdrawalRecord::getWithdrawalState,"1");
        List<WzWithdrawalRecord> list2 =  this.list(lqw2);
        if (ObjectUtils.isNotEmpty(list2)){
            for (int i = 0; i < list2.size(); i++) {
                notAmount +=list2.get(i).getMoney();
            }
        }
        map.put("notTransfer",notAmount); //未打款金额
      WzProgramUser user = wzProgramUserService.getById(id);
      map.put("canWithdrawAmount",user.getCarryCommission()); //用户可提现佣金
        return map;
    }


}

